package com.sdut.material.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdut.material.pojo.Type;
import com.sdut.material.mapper.TypeMapper;
import com.sdut.material.pojo.vo.LayUISelectMVO;
import com.sdut.material.service.ITypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sdut.material.util.JSONResult;
import com.sdut.material.util.LayUITableResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yu
 * @since 2022-04-20
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements ITypeService {
    @Autowired
    private TypeMapper typeMapper;
    @Override
    public LayUITableResult selectByPage(Long page, Long limit) {
        IPage<Type> iPage = new Page<>(page,limit);
        IPage<Type> result = typeMapper.selectPage(iPage,new QueryWrapper<>());
        return LayUITableResult.ok(result.getTotal(),result.getRecords());
    }

    @Override
    public JSONResult insert(Type type) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("name",type.getName());
        if (typeMapper.selectOne(queryWrapper) != null) {
            return JSONResult.error("该名称已存在添加失败");
        }
        typeMapper.insert(type);
        return JSONResult.ok("添加成功");
    }

    @Override
    public Type selectById(Integer typeId) {
        Type type = typeMapper.selectById(typeId);
        return type;
    }

    @Override
    public void updateType(Type type) {
        typeMapper.updateById(type);
    }

    @Override
    public void deleteById(Integer typeId) {
        typeMapper.deleteById(typeId);
    }

    @Override
    public JSONResult selectAllTypes() {
        List<Type> typeList = typeMapper.selectList(new QueryWrapper<>());
        List<LayUISelectMVO> layUISelectMVOList = new ArrayList<>();
        for (Type type : typeList) {
            LayUISelectMVO layUISelectMVO = new LayUISelectMVO();
            layUISelectMVO.setId(type.getId());
            layUISelectMVO.setName(type.getName());
            layUISelectMVO.setStatus(1);
            layUISelectMVOList.add(layUISelectMVO);
        }
        return JSONResult.ok(layUISelectMVOList);
    }
}
